import { useStore } from 'vuex'
import { ComputedRef, ref, computed } from 'vue'

interface LoadParams { // 请求数据类型接口
  currentPage: number;
  pageSize: number;
  id?: string;
}
// 数据页数和数据条数请求的方法                    total 为总数据数、是一个computed属性值
export const useLoadMore = (actionName: string, total: ComputedRef<number>, params: LoadParams = { currentPage: 2, pageSize: 5, id: '' }) => {
  const store = useStore()
  const currentPage = ref(params.currentPage) // 统计加载到第几页
  const requestParams = computed(() => ({ // 发送请求需要的页数和 一页需要多少条数据
    currentPage: currentPage.value,
    pageSize: params.pageSize
  }))
  const loadMorePage = () => { // 发送请求 然后对页数+1操作
    store.dispatch(actionName, { ...requestParams.value, id: params.id }).then(() => {
      currentPage.value++
    })
  }
  const isLastPage = computed(() => { // 计算页面是否是最后一页
    return Math.ceil(total.value / params.pageSize) < currentPage.value
  })

  return { loadMorePage, isLastPage, currentPage }
}
